<template>
	<div class="container">
		<el-upload :accept="accept" action="#" :http-request="uploadRequest" list-type="picture" :show-file-list="false">
			<span class="name" v-if="upload.name">{{upload.name}}</span>
			<el-button size="small" v-else type="primary" :loading="upload.loading" :disabled="upload.loading"><i class="el-icon-upload" v-if="!upload.loading"></i>点击上传</el-button>
		</el-upload>
		<el-button v-if="upload.url" size="small" type="primary" icon="el-icon-view" @click="previewFile(upload.url)">查看</el-button>
	</div>
</template>

<script>
import { uploadFile } from '@/api/common';
export default {
	name: '',
	components: {},
	props: {
		accept: {
			type: String,
			default: '',
		},
		initName: {
			type: String,
			default: '',
		},
		initUrl: {
			type: String,
			default: '',
		},
		isUnzip: {
			type: Boolean,
			default: false,
		},
	},
	data() {
		return {
			upload: {
				name: this.initName,
				loading: false,
				url: this.initUrl,
			},
		};
	},
	watch: {
		initName:{
			handler(newVal, oldVal) {
                this.upload.name = newVal;
            },
            deep: true,
			immediate: true
		},
		initUrl:{
			handler(newVal, oldVal) {
                this.upload.url= newVal;
            },
            deep: true,
			immediate: true
		},
	},
	// 方法
	methods: {
		uploadRequest(e) {
			this.upload.loading = true;
			if (this.accept) {
				const fileName = e.file.name;
				const type = fileName.split('.').pop().toLowerCase();
				if (this.accept.indexOf(type) == -1) {
					this.$message.error('上传格式不正确!');
					this.upload.loading = false;
					return false;
				}
			}
			const formData = new FormData();
			formData.append('file', e.file);
			const date = new Date();
			formData.append(
				'biz',
				'public/' +
					date.getFullYear() +
					'/' +
					parseInt(date.getMonth() + 1)
			);
			uploadFile(formData)
				.then((res) => {
					this.upload = {
						name: res.result.name,
						url: res.result.url,
						loading: false,
					};
					this.$emit('upload', res.result);
				})
				.catch(() => {
					this.upload = {
						loading: false,
					};
				});
		},
		//预览文件
		previewFile(url) {
			window.open(url);
		},
		init(){
			this.upload= {
				name: this.initName,
				loading: false,
				url: this.initUrl,
			}
		}
	},
	// 生命周期 - 创建完成（可以访问当前this实例）
	created() {},
	// 生命周期 - 挂载完成（可以访问DOM元素）
	mounted() {},
};
</script>
<style lang="scss" scoped>
    .name{display: block;text-align: left;}
</style>